import {createRouter, createWebHistory} from 'vue-router'
import {useLoginStore} from './login'
import {ElMessage} from 'element-plus'
import LoginPageVue from '../../components/LoginPage.vue'
import MainPageVue from '../../components/MainPage.vue'
import AppManagerPageVue from '../../components/AppManagerPage.vue'
import RoleManagerPageVue from '../../components/RoleManagerPage.vue'
import UserManagerPageVue from '../../components/UserManagerPage.vue'
import SettingPageVue from '../../components/SettingPage.vue'
import QuickJumpPageVue from '../../components/QuickJumpPage.vue'
import ArticlePageVue from '../../components/ArticlePage.vue'
import HomePageVue from '../../components/HomePage.vue'

// 宏定义路径 绝对路径加'/'
export const vueRouteDefine = {
    // 首页
    index: '/main/home',
    // 其他
    login: '/login',
    main: '/main',
    homePage: 'home',
    appManager: 'app-manager',
    userManager: 'user-manager',
    roleManager: 'role-manager',
    setting: 'setting',
    quickJump: 'quick-jump',
    article: 'article'
}

export const vueRouter = createRouter({
    history: createWebHistory(import.meta.env.VITE_PROJECT_PREFIX),
    routes: [
        // 重定向首页
        {path: '/', redirect: vueRouteDefine.index},
        // 登录
        {path: '/login', name: 'login', component: LoginPageVue},
        // 主界面
        {
            path: '/main', name: 'main', component: MainPageVue, children: [
                {path: vueRouteDefine.homePage, component: HomePageVue},
                {path: vueRouteDefine.appManager, component: AppManagerPageVue},
                {path: vueRouteDefine.userManager, component: UserManagerPageVue},
                {path: vueRouteDefine.roleManager, component: RoleManagerPageVue},
                {path: vueRouteDefine.setting, component: SettingPageVue},
                {path: vueRouteDefine.quickJump, component: QuickJumpPageVue},
                {path: vueRouteDefine.article, component: ArticlePageVue},
            ]
        },
    ]
})

// 导航守卫
// 全局拦截验证
vueRouter.beforeEach(
    (to, _from, next) => {
        console.log("to:" + to.path)
        // 登录页面放行
        if (to.path == '/login') return next()
        // 其他需登录
        const loginStore = useLoginStore()
        if (!loginStore.userId) {
            ElMessage.info('请先登录')
            return next({name: 'login'})
        } else {
            return next()
        }
    }
)